<template>
	<div class='menu-maintain-container'>
		<vxe-grid ref='menuMaintainGridRef' v-bind='gridConfig'>
			<template v-slot:toolbar_buttons>
				<n-button
					v-hasPerm='["systemManagement:menuMaintain:insert"]'
					round strong @click='showAddRootModal'>
					<template v-slot:icon>
						<ClassIcon icon-class='fa fa-plus'/>
					</template>
					新增根菜单
				</n-button>
			</template>
			<template v-slot:toolbar_tools>
				<div class='vxe-custom--wrapper'>
					<n-button circle @click='initGrid(null)'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-refresh'/>
						</template>
					</n-button>
				</div>
			</template>
			<template v-slot:menuIcon='{ row }'>
				<template v-if='row.menuIcon'>
					<template v-if='"svg"===row.menuIconType && row.menuIcon'>
						<template v-if='row.menuIcon.match("fa-")'>
							<SvgIcon icon-type='fa' :icon-class='row.menuIcon'
									 font-size='30px'/>
						</template>
						<template v-if='row.menuIcon.match("iconfont5-")'>
							<SvgIcon icon-type='iconfont5' :icon-class='row.menuIcon'
									 font-size='30px'/>
						</template>
						<template v-if='row.menuIcon.match("customized-")'>
							<SvgIcon icon-type='customized' :icon-class='row.menuIcon'
									 font-size='30px'/>
						</template>
					</template>
					<template v-if='"class"===row.menuIconType'>
						<ClassIcon :icon-class='row.menuIcon' font-size='30px'/>
					</template>
				</template>
			</template>
			<template v-slot:tabIcon='{ row }'>
				<template v-if='row.tabIcon'>
					<template v-if='"svg"===row.tabIconType'>
						<template v-if='row.tabIcon.match("fa-")'>
							<SvgIcon icon-type='fa' :icon-class='row.tabIcon'
									 font-size='30px'/>
						</template>
						<template v-if='row.tabIcon.match("iconfont5-")'>
							<SvgIcon icon-type='iconfont5' :icon-class='row.tabIcon'
									 font-size='30px'/>
						</template>
						<template v-if='row.tabIcon.match("customized-")'>
							<SvgIcon icon-type='customized' :icon-class='row.tabIcon'
									 font-size='30px'/>
						</template>
					</template>
					<template v-if='"class"===row.tabIconType'>
						<ClassIcon :icon-class='row.tabIcon' font-size='30px'/>
					</template>
				</template>
			</template>
			<template v-slot:operate='{ row }'>
				<n-flex justify='space-evenly'>
					<n-button v-hasPerm='["systemManagement:menuMaintain:insert"]'
							  text @click='showAddChildModal(row)'
							  alt='添加下级菜单'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-plus'/>
						</template>
					</n-button>
					<n-button v-hasPerm='["systemManagement:menuMaintain:update"]'
							  text @click='showEditModal(row)'
							  alt='编辑菜单信息'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-edit'/>
						</template>
					</n-button>
					<n-button v-hasPerm='["systemManagement:menuMaintain:delete"]'
							  text @click='remove(row)'
							  alt='删除菜单'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-remove'/>
						</template>
					</n-button>
				</n-flex>
			</template>
		</vxe-grid>
	</div>
	<AddRootModal ref='addRootModalRef' v-bind='AddRootModalConfig'/>
	<AddChildModal ref='addChildModalRef' v-bind='AddChildModalConfig'/>
	<EditModal ref='editModalRef' v-bind='editModalConfig'/>
</template>
<script setup lang='ts'>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { VxeGrid, VxeUI } from '@/config/vxe/index.ts';
import { VxeGridInstance, VxeGridProps, type VxeTableDefines, VxeTablePropTypes } from 'vxe-table';
import { showDictValueByKey1 } from '@/static/js/dict/format.ts';
import axios from '@/config/axios/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import type { MenuProps } from '#/src/components/page/systemManager/menuMaintain/MenuMaintainProps.d.ts';
import type { Dict } from '#/Dictionary.d.ts';
import { loadDict } from '@/config/dictionary/dictionary.ts';
// ---------------------------------------------------------------------
const SvgIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/SvgIcon.vue'));
const ClassIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/ClassIcon.vue'));
const AddRootModal = defineAsyncComponent(() => import('./addRootModal.vue'));
const AddChildModal = defineAsyncComponent(() => import('./addChildModal.vue'));
const EditModal = defineAsyncComponent(() => import('./editModal.vue'));
// ---------------------------------------------------------------------
const menuMaintainGridRef = ref<VxeGridInstance>();
const addRootModalRef = ref<InstanceType<typeof AddRootModal>>();
const addChildModalRef = ref<InstanceType<typeof AddChildModal>>();
const editModalRef = ref<InstanceType<typeof EditModal>>();
// ---------------------------------------------------------------------
const dict = reactive<Dict>({});
// ---------------------------------------------------------------------
const gridConfig = reactive<VxeGridProps>({
	loading        : false,
	stripe         : false,
	height         : 'auto',
	align          : 'center',
	keyboardConfig : { isArrow : true },
	pagerConfig    : {
		enabled : false
	},
	toolbarConfig  : {},
	formConfig     : {
		enabled : false,
		data    : {}
	},
	checkboxConfig : {
		range : false
	},
	rowConfig      : {
		useKey   : true,
		keyField : 'id'
	},
	treeConfig     : {
		lazy          : true,
		accordion     : true,
		reserve       : false,
		showLine      : true,
		trigger       : 'default',
		rowField      : 'menuCode',
		hasChildField : 'hasChild',
		childrenField : 'children',
		loadMethod    : ({ row }) => initGrid(row)
	},
	columns        : [
		/*{
		 field        : 'id',
		 title        : '菜单唯一编号',
		 treeNode     : true,
		 showOverflow : 'tooltip'
		 },*/
		{
			field        : 'menuCode',
			title        : '菜单编码',
			treeNode     : true,
			showOverflow : 'tooltip'
		},
		{
			field        : 'menuName',
			title        : '菜单名称',
			showOverflow : 'tooltip'
		},
		{
			field        : 'menuType',
			title        : '菜单类型',
			showOverflow : 'tooltip',
			formatter    : (params: {
				cellValue: any,
				column: VxeTableDefines.ColumnInfo<VxeTablePropTypes.Row>,
				row: VxeTablePropTypes.Row
			}) => {
				return showDictValueByKey1('menuType', dict, params.cellValue);
			}
		},
		{
			field        : 'menuPath',
			title        : '菜单路径',
			showOverflow : 'tooltip'
		},
		/*{
		 field        : 'menuIconType',
		 title        : '菜单图标类型',
		 titleSuffix  : {
		 content : '图标类型仅支持字体图标和svg图标'
		 },
		 showOverflow : 'tooltip'
		 },*/
		{
			field        : 'menuIcon',
			title        : '菜单图标',
			showOverflow : 'tooltip',
			slots        : {
				default : 'menuIcon'
			}
		},
		/*{
		 field        : 'tabIconType',
		 title        : '标签栏图标类型',
		 titleSuffix  : {
		 content : '图标类型仅支持字体图标和svg图标'
		 },
		 showOverflow : 'tooltip'
		 },*/
		{
			field        : 'tabIcon',
			title        : '标签栏图标',
			showOverflow : 'tooltip',
			slots        : {
				default : 'tabIcon'
			}
		},
		{
			field       : 'isCache',
			title       : '是否保活',
			titleSuffix : {
				content : '选择保活,切换标签栏的时候不会销毁DOM\n选择销毁,切换标签栏的时候会直接销毁DOM'
			},
			cellRender  : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '保活',
						unchecked : '销毁'
					}
				},
				events : {
					toggleEvent : (row: any) => toggleIsCache(row)
				}
			}
		},
		{
			field       : 'status',
			title       : '是否启用',
			titleSuffix : {
				content : '选择启用该菜单,可以在角色编辑界面查看到该菜单,\n并能够展示在拥有访问权限的用户菜单栏中'
			},
			cellRender  : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '启用',
						unchecked : '禁用'
					}
				},
				events : {
					toggleEvent : (row: any) => toggleStatus(row)
				}
			}
		},
		{
			field        : 'sort',
			title        : '序号',
			showOverflow : 'tooltip'
		},
		{
			title        : '操作',
			showOverflow : 'tooltip',
			slots        : {
				// 使用 JSX 渲染
				default : 'operate'
			}
		}
	],
	data           : [],
	// @ts-ignore
	// onPageChange : (params: any) => changePage(params),
	// @ts-ignore
	onFormSubmit : () => queryCondition()
});
const AddRootModalConfig = reactive({
	reLoad : () => initGrid(null),
	dict   : dict
});
const AddChildModalConfig = reactive({
	reLoad : () => initGrid(null),
	dict   : dict
});
const editModalConfig = reactive({
	reLoad : () => initGrid(null),
	dict   : dict
});
// ---------------------------------------------------------------------
const props = defineProps({
	params : {
		type    : Object,
		require : false,
		default : null
	}
});
// ---------------------------------------------------------------------
onMounted(async () => {
	initDict().then(() => {
		initGrid(null);
	});
});
const initDict = async (): Promise<void> => {
	return loadDict([
		'menuType',
		'iconType'
	]).then((dictResult: Dict) => {
		// 合并字典
		Object.assign(dict, dictResult);
	});
};
const initGrid = async (row: any): Promise<any[]> => {
	gridConfig['loading'] = true;
	return new Promise((resolve, reject) => {
		menuMaintainGridRef.value?.clearCurrentRow();
		menuMaintainGridRef.value?.clearCurrentColumn();
		// 一定要清空掉树数据,不然其他已展开节点是不重载的
		menuMaintainGridRef.value?.clearTreeExpand();
		// 判断是否懒加载模式
		if (row) {
			gridConfig.formConfig!.data.menuCode = row.menuCode;
		} else {
			gridConfig.formConfig!.data.menuCode = '0';
		}
		/*axios<any, JsonResultProps<any>, any>({
		 method : 'GET',
		 url    : '/cache/getCacheStats'
		 }).then((jsonResult: JsonResultProps<any>) => {
		 VxeUI.modal.message({
		 content : jsonResult.data,
		 status  : 'warning',
		 id      : 'failedMessage'
		 });
		 }).catch((error: unknown) => {
		 VxeUI.modal.message({
		 content : '系统异常,请稍后再试',
		 status  : 'error',
		 id      : 'errorMessage'
		 });
		 reject();
		 });*/
		axios<any, JsonResultProps<any>, any>({
			method : 'POST',
			url    : '/menu/menuTree/lazyLoad',
			data   : gridConfig.formConfig!.data
		}).then((jsonResult: JsonResultProps<any>) => {
			if (jsonResult['status']) {
				if (row) {
					resolve(jsonResult['data']);
				} else {
					gridConfig['data'] = jsonResult['data'];
				}
				gridConfig['loading'] = false;
			} else {
				VxeUI.modal.message({
					content : jsonResult['msg'],
					status  : 'warning',
					id      : 'failedMessage'
				});
			}
		}).catch((error: unknown) => {
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
			reject();
		});
	});
};
const queryCondition = () => {
	initGrid(null);
};
const toggleIsCache = async (rowData: MenuProps) => {
	gridConfig['loading'] = true;
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/menu/isCache/${rowData.menuCode}`
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'success',
				id      : 'successMessage'
			});
		} else {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
		gridConfig['loading'] = false;
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
		gridConfig['loading'] = false;
	});
};
const toggleStatus = async (rowData: MenuProps) => {
	gridConfig['loading'] = true;
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/menu/status/${rowData.menuCode}`
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'success',
				id      : 'successMessage'
			});
		} else {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
		gridConfig['loading'] = false;
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
		gridConfig['loading'] = false;
	});
};
const showAddRootModal = async () => {
	addRootModalRef.value?.showModal();
};
const showAddChildModal = async (rowData: MenuProps) => {
	addChildModalRef.value?.showModal(rowData);
};
const showEditModal = async (rowData: MenuProps) => {
	editModalRef.value?.showModal(rowData);
};
const remove = async (rowData: any) => {
	VxeUI.modal.confirm({
		content : '您确定要删除该菜单吗?',
		title   : '确认删除',
		id      : 'deleteModalUnique'
	}).then((type: any) => {
		if ('confirm' === type) {
			axios<any, JsonResultProps<any>, any>({
				method : 'DELETE',
				url    : `/menu/${rowData.menuCode}`
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					initGrid(null);
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
</script>
<style scoped lang='scss'>
.menu-maintain-container{
	box-sizing :border-box;
	margin     :0;
	padding    :0;
	border     :0;
	height     :100%;
	width      :100%;
}
</style>